<?php
/**
 * Created by PhpStorm.
 * User: Rain
 * Date: 2019/9/10
 * Time: 17:46
 */

namespace Rain\Admin\Services\Business\Controllers;


use Rain\Admin\Services\Models\AdminRoleModel;
use Illuminate\Support\Facades\DB;

class AdminRoleService extends Base
{
    static protected $instance;

    /**
     * 依赖包管理
     *
     * @var array
     */
    protected $rely = [
        'mRole' => AdminRoleModel::class,
    ];

    /**
     * 获取 用户列表
     *
     * @return mixed
     */
    public function getList(){
        $list = $this -> mRole -> roleList($this -> clearWhere());

        return $list;
    }

    /**
     * 获取 权限列表
     *
     * @return mixed
     */
    public function getRuleList(){
        $list = $this -> mRole -> ruleList() -> toArray();

        // 处理权限数据
        $arr = [];
        foreach($list as $k => $v){
            if(!isset($arr[$v['class_id']])) $arr[$v['class_id']] = [];

            $arr[$v['class_id']][] = $v;
        }

        // 权限分类
        $classList = $this -> mRole -> classList(array_keys($arr)) -> toArray();
        foreach($classList as $k => $v){
            if($arr[$v['class_id']]) $classList[$k]['rules'] = $arr[$v['class_id']];

            unset($classList[$k]['class_id']);
        }

        return $classList;
    }

    /**
     * 获取 角色信息
     */
    public function find()
    {
        $id = $this->data;

        $result = $this->mRole->roleFind($id);
        if (!$result) return $result;

        $result['id'] = $result['role_id'];
        unset($result['role_id']);

        return $result;
    }

    /**
     * 操作
     *
     * @param int $id
     * @return int
     */
    public function operating($id = 0){
        $params = $this -> data;

        // 权限id
        $ruleIds = $this -> mRole -> getRuleIds(json_decode($params['rule_ids'], true));

        // 需操作的数据
        $data = [
            'name' => $params['name'],
            'description' => $params['description']
        ];

        DB::beginTRansaction();

        try {
            if(!$id) {
                $this -> mRole -> addRole($data, $ruleIds);
            } else {
                $this -> mRole -> editRole($id, $data, $ruleIds);
            }

            DB::commit();

            return 200;
        } catch (\Exception $exception) {
            DB::rollBack();

            return 800;
        }
    }

    /**
     * 删除角色
     */
    public function del(){
        $id = $this -> data;

        // 超级管理员角色不允许删除
        if(1 == $id) return 800;

        // 角色被绑定则不允许删除
        if($this -> mRole -> isBindUser(14)) return 700;

        DB::beginTransaction();

        try {
            $this -> mRole -> delRole($id);

            DB::commit();

            return 200;
        } catch (\Exception $exception) {
            DB::rollBack();

            return 800;
        }
    }
}
